﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace JKF.Substructure
{
    public static class Sqls
    {
        private static XElement _root;

        public static XElement Root
        {
            get
            {
                string path = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/BusinessLayerSqls.xml");
                if (System.Web.HttpContext.Current.IsDebuggingEnabled)
                {
                    return System.Xml.Linq.XDocument.Load(path).FirstNode as XElement;
                }
                if (_root == null)
                {
                    var doc = System.Xml.Linq.XDocument.Load(path);
                    _root = doc.FirstNode as XElement;
                }
                return _root;
            }
        }

        public static string GetSQL(this object obj, int index)
        {
            var root = Root;
            var cls = root.Elements("class").Single(a => a.Attribute("name").Value == obj.GetType().FullName);
            return cls.Elements("sql").ElementAt(index).Value.Trim();

        }

        public static string GetSQL(this object obj, string name)
        {
            var root = Root;
            var cls = root.Elements("class").Single(a => a.Attribute("name").Value == obj.GetType().FullName);
            return cls.Elements("sql").Single(a => a.Attribute("name").Value == name).Value.Trim();
        }
    }
}
